<?php

namespace app\controller;

use app\BaseController;
use mysqlversion\MysqlVersion;
use app\models\Sql;
use think\facade\View;

class Index extends BaseController
{
    public function initialize()
    {
        $isLogin = app()->session->get('isLogin');
        if(empty($isLogin)) {
            halt('请先登入');
        }
    }

    public function index()
    {
        $get = app()->request->get();
        $page = $get['page'] ?? 1;

        $list = Sql::page($page, 20)
                    ->order('id', 'asc')
                    ->select()
                    ->toArray();

        $count = Sql::count();

        View::assign('list', $list);
        View::assign('page', $page);
        View::assign('count', $count);
        View::assign('pageNum', ceil($count / 20));

        return View::fetch('index/index');

    }


    public function add()
    {
        $post = [];
        $post['author'] = app()->request->post('author', '', 'trim');
        $post['note'] = app()->request->post('note', '', 'trim');
        $post['content'] = app()->request->post('content', '', 'trim');

        if(empty($post['author'])) {
            halt('作者不能为空');
        }

        if(empty($post['note'])) {
            halt('说明不能为空');
        }

        if(empty($post['content'])) {
            halt('SQL不能为空');
        }

        $model = new Sql($post);
        $model->save();

        return redirect('/index/index');
    }

}
